package cn.qf.shop.controller;


import cn.qf.shop.alipay.config.AlipayConfig;
import cn.qf.shop.mapper.OrdersMapper;
import cn.qf.shop.service.OrdersService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * 在支付后的同步通知和异步通知的servlet
 *
 * @author cxf
 */
@Controller
@RequestMapping("/callBack")
@Api(tags = "回调接口")
public class AliPayNofityController extends HttpServlet {


    /**
     * 初始化
     * orders模块业务逻辑层对象
     */
    @Resource
    private OrdersMapper ordersMapper ;

    /**
     * 异步通知Controller
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/asynchronousAdvice", method = RequestMethod.POST)
    @ApiOperation(value = "回调修改订单状态的方法")
    public void asynchronousAdvice(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException {
        System.out.println("这里是异步通知");
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号

        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易号



        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, "RSA2");

        if (verify_result) {
            System.out.println("验证成功！！！");
            System.out.println("获取的订单编号："+out_trade_no);

            //将订单状态由0（待支付）改为 1（已支付，待发货）
            ordersMapper.updatePayStatus(out_trade_no);
            System.out.println("修改订单状态成功！！！");

            //支付宝要求必须返回success，不然就会一直给你回调
            PrintWriter writer = null;
            writer = response.getWriter();
            writer.write("success"); // 一定要打印success
            writer.flush();
            return;
        }else{
            System.out.println("验证失败！！！");
            //支付宝要求必须返回fail，不然就会一直给你回调
            PrintWriter writer = null;
            writer = response.getWriter();
            writer.write("fail"); // 一定要打印fail
            writer.flush();
            return;
        }

    }

    /**
     * 同步通知Controller
     *
     * @param request
     * @param response
     */

    @RequestMapping(value = "/synchronizationAdvice", method = RequestMethod.GET)
    @ApiOperation(value = "回调跳转页面的方法")
    public void synchronizationAdvice(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("这里是同步通知");

        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
//
        System.out.println("获取的订单编号："+out_trade_no);
//        ordersMapper.updatePayStatus(out_trade_no);
//        System.out.println("修改订单状态成功！！！");

        String url = "/shop-app/orders/paySuccess.html?";
        String URL = url + out_trade_no ;
        //跳转到订单页面
        try {
            //重定向
            System.out.println("跳转至支付成功页面！！！");
            response.sendRedirect(URL);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //支付宝要求必须返回success，不然就会一直给你回调
        PrintWriter writer = null;
        writer = response.getWriter();
        writer.write("success"); // 一定要打印success
        writer.flush();
        return;
    }
}
